<template>
  <j-modal :title="title" :width="width" :visible="visible" @ok="handleOk" :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }" @cancel="handleCancel" cancelText="关闭">
    <BasicTree
      ref="treeRef"
      :style="{ minWidth: '250px' }"
      selectable
      search
      @select="onDepSelect"
      :load-data="loadChildrenTreeData"
      :treeData="departTree"
      :selectedKeys="selectedDepIds"
      :expandedKeys="expandedKeys"
      :clickRowToExpand="false"
    ></BasicTree>
  </j-modal>
</template>

<script lang="ts" setup>
  import { ref, nextTick, defineExpose, unref } from 'vue';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDeptList } from '/@/api/demo/system';
  import { queryDepartTreeSync,queryDeptInfoById } from '/@/views/system/depart/depart.api';
  
  const title = ref<string>('');
  const width = ref<number>(600);
  const visible = ref<boolean>(false);
  const disableSubmit = ref<boolean>(false);
  const registerForm = ref();
  const emit = defineEmits(['register', 'success']);
  const treeRef = ref();
  const departTree = ref([]);
  const selectedDepIds = ref([]);
  const expandedKeys = ref([]);
  const selectKey = ref<string>('');

  /**
   * 新增
   */
  function openIntraEnterpriseModel() {
    title.value = '新增';
    visible.value = true;
    loadTreeData();
  }
  
  async function loadTreeData() {
    queryDepartTreeSync().then((res) => {
      if (res) {
        departTree.value = res;
      }
    });
  }
  
  /**
   * 加载子级部门
   */
  async function loadChildrenTreeData(treeNode) {
    try {
      const result = await queryDepartTreeSync({
        pid: treeNode.eventKey,
      });
      const asyncTreeAction = unref(treeRef);
      if (asyncTreeAction) {
        asyncTreeAction.updateNodeByKey(treeNode.eventKey, { children: result });
        asyncTreeAction.setExpandedKeys([treeNode.eventKey, ...asyncTreeAction.getExpandedKeys()]);
      }
    } catch (e) {
      console.error(e);
    }
    return Promise.resolve();
  }
  
  /**
   * 点击选中对应的数节点
   */
  function onDepSelect(keys) {
    selectKey.value = keys;
  }
  
  /**
   * 确定按钮点击事件
   */
  function handleOk() {
    queryDeptInfoById({id:selectKey.value[0]}).then((result) => {
      emit('success',{deptId:result.id,departName:result.departName});
      visible.value = false;
    });
  }

  /**
   * 取消按钮回调事件
   */
  function handleCancel() {
    visible.value = false;
  }

  defineExpose({
    openIntraEnterpriseModel,
    disableSubmit,
  });
</script>

<style lang="less">
  /**隐藏样式-modal确定按钮 */
  .jee-hidden {
    display: none !important;
  }
</style>
<style lang="less" scoped></style>
